<?php
class CartAction extends CommonAction {
	protected $cart;
	protected $user_id;
	protected $condition;
	protected $cartDBdata;
	protected $isbargain;
	public function display($temp = ''){
		$Systempages = M('Systempages') -> where(array('site_id' => __SITEID__,'groupname' => strtolower(GROUP_NAME), 'modelname' => strtolower(MODULE_NAME), 'actionname' => strtolower(ACTION_NAME))) -> find();
		if($Systempages){
			$ModulesDB = D('Modules');
			$this->initView();
			echo $this->view -> fetch('Public:header');
			echo $ModulesDB->getListToString($Systempages['page_view_id'],$this->view,false);
			echo $this->view -> fetch('Public:footer');
			echo $this->view -> fetch('Public:footerscript');
		}else{
			parent::display($temp);
		}
	}
	
	public function _initialize() {
		parent::_initialize ();
		$this->initView();
		parent::getCommomModules($this->view);
		import('ORG.Util.Cookie');
		import ( '@.ORG.CartCookie' );
		$this->cart = new CartCookie ();
		$this->user_id = session('memberInfo')?$this->memberInfo['id']:0;


		$this->condition ['user_id'] = $this->user_id;
		
		$cartdb = M ( 'Cart' );
		$data = $cartdb->where ( $this->condition )->find ();
		//
		$this->cartDBdata=unserialize($data['cartdata']);
		
	}
	public function index() {
		$cartdata = $this->cart->readCart ();
		if($this->user_id>0){
			$this->savetodb();
			$cartdata=$this->readfromdb();
		}else{ 
			//判断用户是否需要登录，如果用户选择登录，跳转到登录页
			$isLogin=$this->_get('isLogin');
			if($isLogin==1){
				session('jumpurl', __SELF__);
				redirect(U('Member/Public/login'));
			}
		}
		$this->assign('total',$this->getTotal($cartdata)) ;
		$productList = $this->getAllProduct($cartdata);
		$this->assign ( 'productList', $productList );
		$this->assign ( 'cartdata', $cartdata );
		if(isMobile()){
			//$this->display ('Mobileindex');
			$this->display ();
		}else{
			$this->display ();
		}
	}
	//AJAX返回订单总额
	public function echoTotal(){
		$cartdata = $this->cart->readCart ();
		if($this->user_id>0){
			$this->savetodb();
			$cartdata=$this->readfromdb();
		}
	    echo $this->getTotal($cartdata);
    }

	//填写订单信息
	public function checkOut(){
		//询问是否登录会员
		if($this->user_id == 0){
			redirect(U('Member/Public/login'));
		}
		$this -> ShippingList = D('Shipping') -> where(array('status' => 1, 'site_id' => __SITEID__)) -> select();
		$this -> InvoiceList = D('Invoice') -> where(array('status' => 1, 'site_id' => __SITEID__)) -> select();
		//dump($this->ShippingList);
		$cartdata = $this->cart->readCart ();
		if($this->user_id>0){
			$this->savetodb();
			$cartdata=$this->readfromdb();
		}
		if(!$cartdata){
			$this->error('购物车是空的');
		}
		$total = $this->getTotal($cartdata);
		$this->assign('total',$total);
		$productList = $this->getAllProduct($cartdata);

		//是否免运费
		$noshipping = true;
		foreach($productList as $v){
			if($v['need_shipping'] == 1){$noshipping = false;}
		}
		if($noshipping){
			$this->noshipping = 1;
		}else{
			$this->noshipping = 0;
		}

		if($this->user_id > 0){
			$this->integral_pay = $this->integral_pay_array($productList, false, 0);
			$this->integral = $this->getIntegral();
		}

		$znum = $this->getnum($cartdata);
		$this->assign ( 'znum', $znum );//商品总数量
		$this->assign ( 'productList', $productList );
		$this->assign ('cartdata',$cartdata);
		$address1 = M('address')->where(array('member_id' => $this->user_id)) ->find();
		//		AliceXT 重修页面逻辑20160518
		$address_id = intval($_GET['address_id']) > 0 ? intval($_GET['address_id']) : (!empty($address1) ? $address1['id'] : 0);
		if($address_id){
			$map['id'] = $address_id;
			$address = M('address')->where($map)->find();
			if($address){
				$this->assign('yourname',$address['yourname']);
				$this->assign('tel',$address['tel']);
				$this->assign('address',$address['address']);
				$this->assign('regionids',$address['regionids']);
			}
		}else{
			if($this->is_weixin()){
//					exit("测试进入微信接口");
				Vendor('Weixin.Weixin');
				$d['token'] = getSysVal('token');
				$d['appid'] = getSysVal('appid');
				$d['appsecret'] = getSysVal('appsecret');
				$this->weixin = new WeixinChat($d);
				$this->assign('addressSign_info', $this->weixin->getSignPackage());
			}
		}
		// AliceXT coupon use
		// 选出可以用的coupon
		$coupons = $this->myCoupons($total);
		// exit(dump($coupons));
		$this->assign('coupons',$coupons);
		$this->display ('MobilecheckOut');
	}
	//填写订单信息
	public function checkOut2(){
		//询问是否登录会员
		if($this->user_id == 0){
			redirect(U('Member/Public/login'));
		}
		$this -> ShippingList = D('Shipping') -> where(array('status' => 1, 'site_id' => __SITEID__)) -> select();
		$this -> InvoiceList = D('Invoice') -> where(array('status' => 1, 'site_id' => __SITEID__)) -> select();

		$cartdata = $this->cart->readCart ();
		if($this->user_id>0){
			$this->savetodb();
			$cartdata=$this->readfromdb();
		}
		if(!$cartdata){
			$this->error('购物车是空的');
		}
		$total = $this->getTotal($cartdata);
		$this->assign('total',$total);
		$productList = $this->getAllProduct($cartdata);
		$productsupplier = array();
		foreach($productList as $k => $v){
			unset($v['content']);
			$productsupplier[$v['supplier_id']][] = $v;
			$memberid=D('Supplier')->where('id = '.$v['supplier_id'])->getfield('member_id');
			$shippinglist[$v['supplier_id']]=D('shipping')->where('member_id = '.$memberid.' and status = 1 ')->select();
		}
		$this->shippinglist=$shippinglist;
//		var_dump($productsupplier);
//		是否免运费
		$noshipping = true;
		foreach($productList as $v){
			if($v['need_shipping'] == 1){$noshipping = false;}
		}
		if($noshipping){
			$this->noshipping = 1;
		}else{
			$this->noshipping = 0;
		}

		if($this->user_id > 0){
			$this->integral_pay = $this->integral_pay_array($productList, false, 0);
			$this->integral = $this->getIntegral();
		}

		$znum = $this->getnum($cartdata);
		$this->assign ( 'znum', $znum );//商品总数量
		$this->assign ( 'productList', $productsupplier );
		$this->assign ('cartdata',$cartdata);
		$address1 = M('address')->where(array('member_id' => $this->user_id)) ->find();
		//		AliceXT 重修页面逻辑20160518
		$address_id = intval($_GET['address_id']) > 0 ? intval($_GET['address_id']) : (!empty($address1) ? $address1['id'] : 0);
		if($address_id){
			$map['id'] = $address_id;
			$address = M('address')->where($map)->find();
			if($address){
				$this->assign('yourname',$address['yourname']);
				$this->assign('tel',$address['tel']);
				$this->assign('address',$address['address']);
				$this->assign('regionids',$address['regionids']);
			}
		}else{
			if($this->is_weixin()){
//					exit("测试进入微信接口");
				Vendor('Weixin.Weixin');
				$d['token'] = getSysVal('token');
				$d['appid'] = getSysVal('appid');
				$d['appsecret'] = getSysVal('appsecret');
				$this->weixin = new WeixinChat($d);
				$this->assign('addressSign_info', $this->weixin->getSignPackage());
			}
		}
		// AliceXT coupon use
		// 选出可以用的coupon
		$coupons = $this->myCoupons($total);
		// exit(dump($coupons));
		$this->assign('coupons',$coupons);
		$this->display ('checkOut');
	}
	//	保存收货地址到数据库
//	参数：收货人、电话、地址
	public function saveAddress($yourname="",$tel="",$address="", $area = ''){
		$yourname = empty($yourname) ? $_POST['yourname'] : $yourname;
		$tel = empty($tel) ? $_POST['tel'] : $tel;
		$address = empty($address) ? $_POST['address'] : $address;

		if(empty($yourname) || empty($tel) || empty($address)){
			return false;
		}else{
			$data['yourname'] = $yourname;
			$data['tel'] =$tel;
			$data['address'] = $address;
			$data['member_id'] = $this->user_id;
			$data['regionids'] = $area;
			$data['site_id'] = __SITEID__;
		    $data[C('TOKEN_ON')] = $_POST[C('TOKEN_ON')];
			$Address = M('address');
			$address = $Address->where($data)->find();
			// 确保地址没被重复保存
			if(empty($address)){
				$Address->add($data);
				return true;
			}else{
				return false;
			}
		}
	}

//	展示该用户的收货地址
	public function showAddress(){
//		处理添加地址
		if(IS_POST){
			$yourname = $this->_post('yourname');
			$area = $this->_POST('area');
			$tel = $this->_post('tel');
			$address = $this->_post('address');
			$shen = getRegionById($area[0]);
			$shi = getRegionById($area[1]);
			$qu =getRegionById($area[2]);
			$address = $shen[0]['region_name'].$shi[0]['region_name'].$qu[0]['region_name'].$address;
			$regionids = ','.implode(',', $area).',';
//			保存地址
			$this->saveAddress($yourname,$tel,$address, $regionids);
			$this->success("保存成功",U('showAddress'));

		}else{
			$Address = M("address");
			$map['site_id'] = __SITEID__;
			$map['member_id'] = $this->user_id;
			$address = $Address->where($map)->select();
			$this->assign("address",$address);
			$this->display();
		}
	}
	//选择新增收货地址
	public function address(){
		
	  $this->display();	
	}
	
	// 选择可以用的优惠券
	public function myCoupons($total){
		$member_id = $this->user_id;
		$site_id = __SITEID__;

		$map['member_id'] = $member_id;
		$map['site_id'] = $site_id;
		$map['use_time'] = '';

		$sns = M('coupon_sn')->where($map)->select();
		import("@.ORG.Coupon.Coupon");
		foreach($sns as $sn){
			$Coupon = new Coupon($sn['id'],'1');
			$flag = $Coupon->canUse();
			if($flag && $Coupon->coupon['full'] < $total){
				$sn['title'] = $Coupon->coupon['title'];
				$sn['full'] = $Coupon->coupon['full'];
				$sn['discount'] = $Coupon->coupon['discount'];
				$arr[] = $sn;
			}
		}
		return $arr;
	}
	public function integralPayRet($cartdata, $confirm = false){
		$num = $this->_post('integral');
		$product = $this->getAllProduct($cartdata);
		$ret = $this->integral_pay_array($product, $confirm, $num);
		if(is_array($ret)){
			return $ret;
		}else{
			return 0;
		}
	}
	
	public function integralPay($cartdata, $confirm = false){
		$ret = $this->integralPayRet($cartdata, $confirm);
		return $ret['money'];
	}
	public function echointegralPay(){
		$data['status'] = 1;
		$data['info'] = '';
		$cartdata = $this->cart->readCart ();
		if($this->user_id>0){
			$this->savetodb();
			$cartdata=$this->readfromdb();
		}
		$data['total'] = $this->getTotal($cartdata);
		$data['total'] += $this->getInvoiceFee($data['total']);
		
		$payRet = $this->integralPayRet($cartdata);
		$data['integralPay'] = $payRet['money'];
		$data['integralsum'] = $payRet['integralsum'];
		echo json_encode($data);
		
	}
	
	
	
	//积分抵现
	private function integral_pay_array($product = array(), $confirm = false, $num = 0){
		$typelist = M('Integral_type') -> where(array('site_id' => __SITEID__)) -> select();
		$ret = array();
		foreach($typelist as $k => $v){
			import("@.ORG.Integrals.".$v['typename']);
			$class = $v['typename'];
			$integral = new $class($this->user_id);
			$integral_pay_arrayret = $integral -> integral_pay_array($product, $confirm, $num);
			if(is_array($integral_pay_arrayret)){
				$ret = $integral_pay_arrayret;
			}
		}
		
		if(empty($ret)){
			return false;
		}else{
			
			return $ret;
		}
	}
	
	//获得用户可用作抵现的积分数量
	private function getIntegral(){
		$typelist = M('Integral_type') -> where(array('site_id' => __SITEID__)) -> select();
		$ret = 0;
		foreach($typelist as $k => $v){
			import("@.ORG.Integrals.".$v['typename']);
			$class = $v['typename'];
			$integral = new $class($this->user_id);
			if($integral -> isPay){
				$ret = $integral->num;
			}
		}
		return $ret;
	}
	private function getregionids($father_id=0,$arr=array(), $ret = array()){
		$re=M('Region')->where(array('region_id'=>$father_id))->find();
		if(!is_array($re)){
			return array_reverse($ret);
		}else{
			$ret[] = $re['region_id'];
			$arr[]=$re;
			return $this->getregionids($re['father_id'],$arr, $ret);
		}
	}
	
	//获取运费
	public function getShippingFee($cartdata){
		$product = $this->getAllProduct($cartdata);
		
		//通过微信的地区代码来计算运费
		if(isset($_POST['nationalCode']) && $_POST['nationalCode'] != ''){
			$regionid = M('Region') -> where(array('REGION_CODE' => $_POST['nationalCode'])) -> getField('region_id');
			$regionids = $this->getregionids($regionid);
			
			$_POST['regionids'] = ','.implode(',', $regionids).',';
			
		}
		
		$fee = D('Shipping') -> getExpensesByProduct($this->_post('shipping_id', 'int'), $product, $_POST['regionids']);
		return $fee;
	}

	
	//获取发票费用
	public function getInvoiceFee($total = 0){
		$fee = 0;
		$Invoice = D('Invoice') -> where(array('status' => 1, 'site_id' => __SITEID__, 'id' => $this->_post('invoice_id', 'int'))) -> find();
		if(!$Invoice){return 0;}
		$fee = $Invoice['tax'] * $total;
		return $fee;
	}
	
	
	
	public function echoCoupon(){
		$cartdata = $this->cart->readCart ();
		if($this->user_id>0){
			$this->savetodb();
			$cartdata=$this->readfromdb();
		}
		$total = $this->getTotal($cartdata);
		$total += $this->getInvoiceFee($total);
		
		$ret['total'] = '¥'.($total);
		echo json_encode($ret);
	}
	
	
	public function echoShippingFee(){
		$cartdata = $this->cart->readCart ();
		if($this->user_id>0){
			$this->savetodb();
			$cartdata=$this->readfromdb();
		}
		$fee = $this->getShippingFee($cartdata);
		
		if($fee > 0){
			$ret['shipping_fee'] = '¥'.$fee;
		}else{
			$ret['shipping_fee'] = 0;
		}
		
		$total = $this->getTotal($cartdata);
		$total += $this->getInvoiceFee($total);
		
		$ret['total'] = '¥'.($total);
		echo json_encode($ret);
	}
	public function echoShippingFeell(){
		$cartdata = $this->cart->readCart();
		if($this->user_id>0){
			$this->savetodb();
			$cartdata=$this->readfromdb();
		}
		$fee = $this->getShippingFee1($_POST['shipping_id'],$cartdata);
		foreach($fee as $k => $v){
		    $ret['#Shippingfee_'.$k]=$v;
			$ret['#fee_'.$k]=','.$k.','.$v;
        }
        $fee=array_sum($fee);
		$total = $this->getTotal1($cartdata);//这里没算运费
		$total += $this->getInvoiceFee($total);
        $total += $fee;//这里加上运费
		$ret['total'] = '¥'.($total);
		$ret['fee']=$fee;
		echo json_encode($ret);
	}

	//获取运费
	public function getShippingFee1($shipping_id,$cartdata){
		$product = $this->getAllProduct($cartdata);
		//通过微信的地区代码来计算运费
		if(isset($_POST['nationalCode']) && $_POST['nationalCode'] != ''){
			$regionid = M('Region') -> where(array('REGION_CODE' => $_POST['nationalCode'])) -> getField('region_id');
			$regionids = $this->getregionids($regionid);
			$_POST['regionids'] = ','.implode(',', $regionids).',';
		}
		$fee = D('Shipping') -> getExpensesByProduct3($shipping_id, $product, $_POST['regionids']);
		return $fee;
	}
	//生成订单
	public function createOrder(){
		if(isset($_POST)){
			$orderDB = D('Order');
			$cartdata = $this->cart->readCart ();
			if($this->user_id>0){
				$this->savetodb();
				$cartdata=$this->readfromdb();
				if(empty($cartdata)){
				   $this->error('没有商品，请重新购买');
				}
			}
			$membersaledb = M('Membermembersale');
			$allProduct = $this->getAllProduct($cartdata);
			$member_memberdb = M('Member_member');
			//积分抵现
			//if(__SITEID__ == 13){dump($allProduct);exit;}
			$integral_pay = isset($_POST['integral_pay'])? intval($_POST['integral_pay']) : 0;
			$_POST['integral'] = $integral_pay;
			$shippingfee = $this->getShippingFee($cartdata);
			$_POST['shipping_fee'] = (float)$shippingfee;
			
			//$_POST['area']=implode(',',$_POST['area']);
			//设置为非开通站点订单
			$_POST['siteid'] = 0;
			//设置为非充值订单
			$_POST['savemoney'] = 0;
			$_POST['site_id'] = __SITEID__;
			$_POST['relate_id'] = __RELATEID__;
			$_POST['status'] = 1;//0.已取消 1.待支付 2.已支付
			$_POST['ordernumber'] = build_order_no();
			$_POST['create_time'] = time();
			$_POST['create_date'] = strtotime(date('Y-m-d'));
			$_POST['shipping_id'] = isset($_POST['shipping_id'])?$_POST['shipping_id']:0;
			$_POST['total'] = $this->getTotal($cartdata);
			$_POST['member_id'] = $this->memberInfo['id']?$this->memberInfo['id']:0;
			$_POST['nickname'] = $this->memberInfo['nickname']?$this->memberInfo['nickname']:'';

			$integral_pay_ret = $this->integral_pay_array($allProduct, true, $integral_pay);$_POST['integral_pay'] = $integral_pay_ret['money'] > 0?$integral_pay_ret['integralsum']:0;
			$_POST['pay_type'] = isset($_POST['pay_type'])?$_POST['pay_type']:'';
			//发票
			//推荐订单
			$_POST['aff_id'] = intval($_COOKIE['aff_id']);
			setcookie('aff_id', '', time()-1, '/');
			$_POST['taxtitle'] = isset($_POST['taxtitle'])?$_POST['taxtitle']:'';
			//$_POST['invoice_id'] = isset($_POST['invoice_id'])?intval($_POST['invoice_id']):0;
			$_POST['tax_fee'] = $this->getInvoiceFee($_POST['total']);
			$_POST['total'] += $_POST['tax_fee'];
			
			$_POST['coupon_sn_id'] = (int)$_POST['coupon_sn_id'];
			if(is_array($_POST['Guestbook'])){
				$_POST['Guestbook'] = implode('<br>',$_POST['Guestbook']);
		    }
			/*if(!$orderDB->create()){
			    return false;
			}*/
			$discount=$_POST['total']+$integral_pay_ret['money'];
			$_POST['discount']=$discount-$_POST['total'];
			unset($_POST['integral_pay']);
			$orderId = $orderDB->add($_POST);
			if($orderId){
				// 写入优惠券
				$coupon_sn = $_POST['coupon_sn_id'];
				$Coupon = new Coupon($coupon_sn,"2");
				$_POST['coupon_sn_id']>0 && $Coupon -> setUsed($orderId);
				//写入订单明细
				$saledb = M('Sale');
				$saledata = array();
				$sni = 0;
				foreach($allProduct as $v){
					$saledata['order_id'] = $orderId;
					$saledata['product_id'] = $v['id'];
					$saledata['member_id'] = $_POST['member_id'];
					$saledata['num'] = $v['num'];
					$saledata['buy_num'] =$v['num'];
					$saledata['site_id'] = __SITEID__;
					$saledata['price'] = $v['reprice'] == 0 ? $v['price'] : $v['reprice'];
					$saledata['aff_money'] = $v['reaffmoney'] == 0 ? $v['affmoney'] : $v['reaffmoney']; 
					$saledata['total'] = $v['num']*$saledata['price'];
					$saledata['attr'] = empty($v['attrList'])?'':$v['attrList'];
					//购买时确定由谁发货，首先查找到当前会员的最上家会员
					$member_supplier_id = M('Member_member') -> where(array('smember_id' => $this->user_id)) -> getField('member_id');
					//查找会员对应的供货商对象
					$supplier_member_id = M('Member_supplier') -> where(array('member_id' => $member_supplier_id)) -> getField('supplier_id');
					$saledata['supplier_id'] = empty($v['supplier_id'])?'':$v['supplier_id'];
					if($supplier_member_id > 0){
						$saledata['supplier_id'] = $supplier_member_id;
					}
					$saledata['categoryname'] = $v['categoryname'];
					$saledata['code'] = $v['recode'] != '' ? $v['recode'] : $v['code'];
					$saledata['unit'] = $v['unit'];
					$saledata['create_time'] = $_POST['create_time'];
					$saledata['title'] = $v['title'];
					if(!$this->checkStockCreateOrder($v['id'], $v['num'], $saledata['attr'])){
						//没有库存不能创建订单
						$orderDB -> where(array('id' => $orderId, 'site_id' => __SITEID__)) -> delete();
						$saledb -> where(array('order_id' => $orderId, 'site_id' => __SITEID__)) -> delete();
						$this->error('已售罄，您下手太慢了！');
						exit;
					}
				    $saledata['img_url'] = $v['img_url'];
					
					//分成是否需要审核 
					$saledata['affpass'] = $v['affpass'];
					//处理砍价
					$bprice = $this->productBargain($v['id'],true);
					if($bprice > 0){
						$saledata['price'] = $bprice;
						$saledata['num'] = 1;
						$saledata['total'] = $bprice;
						M('Bargain_order') -> where(array('order_id' => 0, 'member_id' => $this->memberInfo['id'], 'product_id' => $v['id'])) -> data(array('order_id' => $orderId)) -> save();
					}
					$sale_id = $saledb -> data($saledata) -> add();
					//写入销售记录与推荐人关系表
					//下单的人所有上家
					$memberpids = $member_memberdb -> where(array('smember_id' => $saledata['member_id'])) -> select();
					foreach($memberpids as $mk => $mv){
						$membersale['order_id'] = $orderId;
						$membersale['site_id'] = __SITEID__;
						$membersale['sale_id'] = $sale_id;
						$membersale['product_id'] = $v['id'];
						$membersale['dateline'] = $_POST['create_time'];
						$membersale['member_id'] = $mv['member_id'];
						$membersale['deep'] = $mv['deep'];
						$membersale['price'] = $saledata['price'];
						$membersale['aff_money'] = $saledata['aff_money'];
						$membersale['num'] = $saledata['num'];
						$membersale['total'] = $saledata['total'];
						$membersaledb -> add($membersale); 
					}
					if($sni == 0){
						$domain = C('DOMAIN_MAIN');
						$picurl = 'http://'.$domain[0].'/Public'.$v['img_url'];
					}
					$sni ++;
				}
				//下单通知
				$afflist = M('Affiliatesetting') -> where(array('site_id' => __SITEID__, 'status' => 1)) -> select();
				foreach($afflist as $v){
					import("@.ORG.Affiliate.".$v['classname']);
					$class = $v['classname'];
					$Threelevel = new $class($orderId, __SITEID__);
					$Threelevel -> sendMsg();
				}
				//通知当前会员
				if($this->user_id>0){
				//下单会员
				$openid = M('Member') -> where(array('id' => $this->user_id)) -> getField('openid');
				$sendWXNews[0]['title'] = '商城订单通知';
				$sendWXNews[0]['url'] = U('Member/Order/index',array('id' => $orderId),true,false,true);
				$sendWXNews[0]['picurl'] = $picurl;
				$sendWXNews[0]['description'] = '【订单号为：'.$_POST['ordernumber'].'，总金额为：'.$_POST['total'].'】尚未支付，请尽快支付！';
				//$msg = '粉丝下单，订单号为：'.$this->order['ordernumber'].'，分成金额为：'.$money;
				sendWXNews($openid, $sendWXNews);
				}
				//成功后清空购物车
				$this->clearCart();
				$orderDB -> updateStock($orderId);
				if($_POST['total'] == 0){
					D('Order') -> upstate($_POST['ordernumber']);
				    redirect(U('Member/Order/read', array('id' => $orderId)));
				}
				C('URL_MODEL',0);
				redirect(U('Home/Payment/index', array('id' => $orderId),true,false,true));
			}else{
				$this->error($orderDB->getError());
			}
		}else{
			$this->error('非法操作，请填写信息');
		}
	}
    //生成订单
    public function createOrder1(){
        if(isset($_POST)){
            $orderDB = D('Order');
            $cartdata = $this->cart->readCart ();
            if($this->user_id>0){
                $this->savetodb();
                $cartdata=$this->readfromdb();
                if(empty($cartdata)){
                    $this->error('没有商品，请重新购买');
                }
            }
            $membersaledb = M('Membermembersale');
            $allProduct = $this->getAllProduct($cartdata);
            $member_memberdb = M('Member_member');
            //积分抵现
            //if(__SITEID__ == 13){dump($allProduct);exit;}
            $integral_pay = isset($_POST['integral_pay'])? intval($_POST['integral_pay']) : 0;
            $_POST['integral'] = $integral_pay;
//            $shippingfee = $this->getShippingFee1($cartdata);
//            $_POST['shipping_fee'] = (float)$shippingfee;

            //$_POST['area']=implode(',',$_POST['area']);
            //设置为非开通站点订单
            $_POST['siteid'] = 0;
            //设置为非充值订单
            $_POST['savemoney'] = 0;
            $_POST['site_id'] = __SITEID__;
            $_POST['relate_id'] = __RELATEID__;
            $_POST['status'] = 1;//0.已取消 1.待支付 2.已支付
            $_POST['ordernumber'] = build_order_no();
            $_POST['create_time'] = time();
            $_POST['create_date'] = strtotime(date('Y-m-d'));
            $_POST['shipping_id'] = isset($_POST['shipping_id'])?$_POST['shipping_id']:0;
            $_POST['total'] = $this->getTotal1($cartdata);
			$_POST['total']+=$_POST['shipping_fee'];
            $_POST['member_id'] = $this->memberInfo['id']?$this->memberInfo['id']:0;
            $_POST['nickname'] = $this->memberInfo['nickname']?$this->memberInfo['nickname']:'';

            $integral_pay_ret = $this->integral_pay_array($allProduct, true, $integral_pay);$_POST['integral_pay'] = $integral_pay_ret['money'] > 0?$integral_pay_ret['integralsum']:0;
            $_POST['pay_type'] = isset($_POST['pay_type'])?$_POST['pay_type']:'';
            //发票
            //推荐订单
            $_POST['aff_id'] = intval($_COOKIE['aff_id']);
            setcookie('aff_id', '', time()-1, '/');
            $_POST['taxtitle'] = isset($_POST['taxtitle'])?$_POST['taxtitle']:'';
            //$_POST['invoice_id'] = isset($_POST['invoice_id'])?intval($_POST['invoice_id']):0;
            $_POST['tax_fee'] = $this->getInvoiceFee($_POST['total']);
            $_POST['total'] += $_POST['tax_fee'];

            $_POST['coupon_sn_id'] = (int)$_POST['coupon_sn_id'];
            if(is_array($_POST['Guestbook'])){
                $_POST['Guestbook'] = implode('<br>',$_POST['Guestbook']);
            }
            /*if(!$orderDB->create()){
                return false;
            }*/
            $discount=$_POST['total']+$integral_pay_ret['money'];
            $_POST['discount']=$discount-$_POST['total'];
				unset($_POST['integral_pay']);
            $orderId = $orderDB->add($_POST);
            if($orderId){
				//按供货商写入新表
				$orderDB->addgroups($orderId,$_POST);
                // 写入优惠券
                $coupon_sn = $_POST['coupon_sn_id'];
                $Coupon = new Coupon($coupon_sn,"2");
                $_POST['coupon_sn_id']>0 && $Coupon -> setUsed($orderId);
                //写入订单明细
                $saledb = M('Sale');
                $saledata = array();
                $sni = 0;
                foreach($allProduct as $v){
                    $saledata['order_id'] = $orderId;
                    $saledata['product_id'] = $v['id'];
                    $saledata['member_id'] = $_POST['member_id'];
                    $saledata['num'] = $v['num'];
					$saledata['buy_num'] =$v['num'];
                    $saledata['site_id'] = __SITEID__;
                    $saledata['price'] = $v['reprice'] == 0 ? $v['price'] : $v['reprice'];
                    $saledata['aff_money'] = $v['reaffmoney'] == 0 ? $v['affmoney'] : $v['reaffmoney'];
                    $saledata['total'] = $v['num']*$saledata['price'];
                    $saledata['attr'] = empty($v['attrList'])?'':$v['attrList'];
                    //购买时确定由谁发货，首先查找到当前会员的最上家会员
                    $member_supplier_id = M('Member_member') -> where(array('smember_id' => $this->user_id)) -> getField('member_id');
                    //查找会员对应的供货商对象
                    $supplier_member_id = M('Member_supplier') -> where(array('member_id' => $member_supplier_id)) -> getField('supplier_id');
                    $saledata['supplier_id'] = empty($v['supplier_id'])?'':$v['supplier_id'];
                    if($supplier_member_id > 0){
                        $saledata['supplier_id'] = $supplier_member_id;
                    }
                    $saledata['categoryname'] = $v['categoryname'];
                    $saledata['code'] = $v['recode'] != '' ? $v['recode'] : $v['code'];
                    $saledata['unit'] = $v['unit'];
                    $saledata['create_time'] = $_POST['create_time'];
                    $saledata['title'] = $v['title'];
                    if(!$this->checkStockCreateOrder($v['id'], $v['num'], $saledata['attr'])){
                        //没有库存不能创建订单
                        $orderDB -> where(array('id' => $orderId, 'site_id' => __SITEID__)) -> delete();
                        $saledb -> where(array('order_id' => $orderId, 'site_id' => __SITEID__)) -> delete();
                        $this->error('已售罄，您下手太慢了！');
                        exit;
                    }
                    $saledata['img_url'] = $v['img_url'];

                    //分成是否需要审核
                    $saledata['affpass'] = $v['affpass'];
                    //处理砍价
                    $bprice = $this->productBargain($v['id'],true);
                    if($bprice > 0){
                        $saledata['price'] = $bprice;
                        $saledata['num'] = 1;
                        $saledata['total'] = $bprice;
                        M('Bargain_order') -> where(array('order_id' => 0, 'member_id' => $this->memberInfo['id'], 'product_id' => $v['id'])) -> data(array('order_id' => $orderId)) -> save();
                    }
                    $sale_id = $saledb -> data($saledata) -> add();
                    //写入销售记录与推荐人关系表
                    //下单的人所有上家
                    $memberpids = $member_memberdb -> where(array('smember_id' => $saledata['member_id'])) -> select();
                    foreach($memberpids as $mk => $mv){
                        $membersale['order_id'] = $orderId;
                        $membersale['site_id'] = __SITEID__;
                        $membersale['sale_id'] = $sale_id;
                        $membersale['product_id'] = $v['id'];
                        $membersale['dateline'] = $_POST['create_time'];
                        $membersale['member_id'] = $mv['member_id'];
                        $membersale['deep'] = $mv['deep'];
                        $membersale['price'] = $saledata['price'];
                        $membersale['aff_money'] = $saledata['aff_money'];
                        $membersale['num'] = $saledata['num'];
                        $membersale['total'] = $saledata['total'];
                        $membersaledb -> add($membersale);
                    }
                    if($sni == 0){
                        $domain = C('DOMAIN_MAIN');
                        $picurl = 'http://'.$domain[0].'/Public'.$v['img_url'];
                    }
                    $sni ++;
                }
                //下单通知
                $afflist = M('Affiliatesetting') -> where(array('site_id' => __SITEID__, 'status' => 1)) -> select();
                foreach($afflist as $v){
                    import("@.ORG.Affiliate.".$v['classname']);
                    $class = $v['classname'];
                    $Threelevel = new $class($orderId, __SITEID__);
                    $Threelevel -> sendMsg();
                }
                //通知当前会员
                if($this->user_id>0){
                    //下单会员
                    $openid = M('Member') -> where(array('id' => $this->user_id)) -> getField('openid');
                    $sendWXNews[0]['title'] = '商城订单通知';
                    $sendWXNews[0]['url'] = U('Member/Order/index',array('id' => $orderId),true,false,true);
                    $sendWXNews[0]['picurl'] = $picurl;
                    $sendWXNews[0]['description'] = '【订单号为：'.$_POST['ordernumber'].'，总金额为：'.$_POST['total'].'】尚未支付，请尽快支付！';
                    //$msg = '粉丝下单，订单号为：'.$this->order['ordernumber'].'，分成金额为：'.$money;
                    sendWXNews($openid, $sendWXNews);
                }
                //成功后清空购物车
                $this->clearCart();
                $orderDB -> updateStock($orderId);
                if($_POST['total'] == 0){
                    D('Order') -> upstate($_POST['ordernumber']);
                    redirect(U('Member/Order/read', array('id' => $orderId)));
                }
                C('URL_MODEL',0);
                redirect(U('Home/Payment/index', array('id' => $orderId),true,false,true));
            }else{
                $this->error($orderDB->getError());
            }
        }else{
            $this->error('非法操作，请填写信息');
        }
    }
	
	//砍价商品
	public function productBargain($id, $confirm = false){
		$order = (float)M('Bargain_order') -> where(array('product_id' => $id, 'state' => 0, 'member_id' => $this->user_id)) -> order('id desc') -> limit(1) -> getField('sum(bargain_nowprice)');
		if($order > 0){
			if($confirm){
				M('Bargain_order') -> where(array('product_id' => $id, 'state' => 0)) -> data(array('state' => 1,'member_id' => $this->user_id, 'endtime' => time())) -> save();
			} 
			return $order;
		}
		return 0;
	}
	
	//能不能砍价
	public function setBargain(){
		$tables = D('Manage_module') -> getAllTables();
		//砍价的表
		
		$table = C('DB_PREFIX').'bargain';
		$flag = false;
		foreach($tables as $k => $v){
		    if($v == $table){
				$flag = true;
			}
		}
		$this->isbargain = setBargain();
		return $flag;
	}
	
	
	
	
	
	//计算订单总价
	protected function getTotal($cartdata, $confirm = false){
		//查询库存表，确定是否存在属性库存量
		if(!$cartdata){
			return false;
		}
		$totalsum = 0;
		$productList = $this->getAllProduct($cartdata);
		foreach($productList as $k=>$v){
			$totalsum+=$v['price'] * $v['num'];
		}
		//运费
		$totalsum += $this->getShippingFee($cartdata);
		//积分抵现
		$totalsum -= $this->integralPay($cartdata);
		//发票
		//$totalsum += $this->getInvoiceFee($totalsum);
		//优惠券
		// AliceXT 优惠券
		$coupon_sn = $_POST['coupon_sn_id'];
		import("@.ORG.Coupon.Coupon");
		$Coupon = new Coupon($coupon_sn,"2");
		$totalsum -= (float)$Coupon->coupon['discount'];
		//echo $coupon_sn;
		return $totalsum;
	}
	//计算订单总价(暂且不算运费)
	protected function getTotal1($cartdata, $confirm = false){
		//查询库存表，确定是否存在属性库存量
		if(!$cartdata){
			return false;
		}
		$totalsum = 0;
		$productList = $this->getAllProduct($cartdata);
		foreach($productList as $k=>$v){
			$totalsum+=$v['price'] * $v['num'];
		}
		//积分抵现
		$totalsum -= $this->integralPay($cartdata);
		//发票
		//$totalsum += $this->getInvoiceFee($totalsum);
		//优惠券
		// AliceXT 优惠券
		$coupon_sn = $_POST['coupon_sn_id'];
		import("@.ORG.Coupon.Coupon");
		$Coupon = new Coupon($coupon_sn,"2");
		$totalsum -= (float)$Coupon->coupon['discount'];
		//echo $coupon_sn;
		return $totalsum;
	}

	//获取一个商品的优惠价格
	
	public function getPriceByOne(){
		$id = $this->_post('id');
	    $cartdata = $this->cart->readCart ();
		if($this->user_id>0){
			$this->savetodb();
			$cartdata=$this->readfromdb();
		}
		$data[$id] = $cartdata[$id];
		//dump($data);
		$ret = $this->getAllProduct($data);
		echo $ret[$id]['price'];
	}
	
	
	
	//获取所有商品
	protected function getAllProduct($cartdata){
		if(!$cartdata){
			return false;
		}
		$list = array();
		$member = M('Member') -> where(array('id' => $this->user_id)) -> find();
		$stockDB = M('Product_stock');
		$productDB = M('Product');
		foreach($cartdata as $k=>$v){
			$arr = explode(':',$v[0]);
			$ids = $arr[1];
			$map['s.attrList']=array('in',parseAttrId(explode(';',$ids)));
			$map['p.id'] = $arr[0];
			$stock = $stockDB->alias("s")->join("left join __PRODUCT__ AS p on p.id=s.product_id")->Field("s.attrList,p.unit, p.title,p.price,p.code,s.code as recode,p.category_id,s.reprice,s.resocre,p.supplier_id,p.img_url,p.id, p.need_shipping,p.affpass, s.reaffmoney,p.affmoney,p.weight,p.noshippingfee,p.levelpriceconfig,p.numpriceconfig")->where($map)->order('p.supplier_id')->find();
			//$stock[$]['categoryname'] = M('Product_category') -> where(array('id' => $stock['category_id'])) -> getField('title');
			if(is_array($stock)){ 
			    $list[$k] = $stock; 
				$list[$k]['num'] = $v[2];
				$list[$k]['price'] = $stock['reprice'] == 0?$stock['price']:$stock['reprice'];
				$list[$k]['code'] = empty($stock['recode'])? $stock['code'] : $stock['recode'];
				$list[$k]['categoryname'] = M('Product_category') -> where(array('id' => $stock['category_id'])) -> getField('title');
		    }else{
				$list[$k] = $productDB->where(array('id'=>$arr[0]))->find();
				$list[$k]['num'] = $v[2];
			}
			//存在等级价格
				$levelpriceconfig = unserialize($list[$k]['levelpriceconfig']);//if(__SITEID__ == 203) {dump($levelpriceconfig);} 
				if($levelpriceconfig){
					foreach($levelpriceconfig as $lk => $lv){
						
					    if($member['level'] == $lv['levelkey'] && (float)$lv['levelprice'] > 0){
							$list[$k]['price'] = (float)$lv['levelprice'];
						}
						
						if($member['level'] == $lv['levelkey'] && (float)$lv['levelaff'] > 0){
							$list[$k]['affmoney'] = (float)$lv['levelaff'];
						}
						
				    }
				}
				////数量优惠
				$numpriceconfig = unserialize($list[$k]['numpriceconfig']);//if(__SITEID__ == 203) {dump($levelpriceconfig);} 
				if($numpriceconfig){
					$numprice = 0;
					$numaff = 0;
					foreach($numpriceconfig as $nk => $nv){
						if($list[$k]['num'] >= $nv['numkey']){
							if($nv['numaff'] > 0){
								$numaff = (float)$nv['numaff'];
							}
							if($nv['numprice'] > 0){
								$numprice = (float)$nv['numprice'];
							}
						}
					}
					if($numprice < $list[$k]['price'] && $numprice > 0){
						$list[$k]['affmoney'] = $numaff;
						$list[$k]['price'] = $numprice;
					}
				}
			
			
			
			
			
			//处理砍价
			$BargainPrice = $this->productBargain($arr[0]);
			if($BargainPrice > 0){
					$list[$k]['num'] = 1;
					$list[$k]['price'] = $BargainPrice;
					$list[$k]['title'] = $list[$k]['title'].'<span style="color:#f00;">【砍价商品】</span>';
			}
			//处理拼团
			//$BargainPrice = $this->productBargain($arr[0]);
			
			
			if($_COOKIE['grouppurchase'.$v[0]] == 1){
				$Grouppurchase = M('Grouppurchase') -> where(array('product_id' => $arr[0], 'status' => 1, 'end_time' => array('gt', date('Y-m-d')))) -> find();$this->isgrouppurchase = 1;
				
				if($Grouppurchase['price'] > 0){
					$list[$k]['num'] = 1;
					$list[$k]['price'] = $Grouppurchase['price'];
					$list[$k]['title'] = $list[$k]['title'].'<span style="color:#f00;">【拼团商品】</span>';
				}
			}
			
		} 
		 
		
		//获取商品属性 
		$attrvalDB = M('attr_val');
		foreach($list as $k=>$v){
		   
		   $attrval = explode(';',$v['attrList']);
		   $list[$k]['attrmes'] = array();
		   
		   foreach($attrval as $v){ 
		     $mes = $attrvalDB->where(array('id'=>$v))->find();
			 array_push($list[$k]['attrmes'],$mes['val']);
		   }
		   
		}
		return $list;
		
	}
	// 添加物品
	public function insert() {
		
		$this->user_id = session('memberInfo')?$this->memberInfo['id']:0;

		if($this->user_id==0){
		
			if(IS_AJAX){
			exit('对不起,您还没有登录!');
			}else{
			$this->error('对不起，您还没有登录!',U('Member/Public/login'));	
			}
			
		}
		
		if($this->_post('cart')){
			$mylevel=D('Member')->where('id = '.$this->memberInfo['id'])->getfield('level');
			$myshop=D('Supplier')->where('member_id = '.$this->memberInfo['id'])->getfield('id');
			if($myshop){
				$goodid=trim($this->_post('id'),':');
				$goodid=explode(':',$goodid)[0];
				$thisshop=D('Product')->where('id = '.$goodid)->getfield('supplier_id');
				if($mylevel == 1 &&$myshop==$thisshop){
					exit('商家不能购买自己的商品!');
				}
			}
			$goods_id=$this->_post('id');
			$goods_title=$this->_post('title');
			$goods_total=$this->_post('total');
			$goods_price=$this->_post('price');
			$goods_attr=$this->_post('attr');
			$productModel=D('Product');
			$sku = $productModel -> getSKUListByIdStatus($goods_id);
			if(count($sku) > 0){
				
				exit('请选择　'.implode('　', $sku).'　再加入购物车！');
			}
			if(isset($_POST['grouppurchase'.$goods_id])){
				$this -> is_subscribe = M('Member') -> where(array('id' => $this->memberInfo['id'])) -> getField('is_subscribe');
				if($this -> is_subscribe == 0){
					exit('请先关注公众号');
				}
				setcookie('grouppurchase'.$goods_id, $_POST['grouppurchase'.$goods_id], time() + 3600, '/');
			}else{
				setcookie('grouppurchase'.$goods_id, '', time() - 1, '/');
			}
			$this -> checkStock($goods_id, $goods_total);
			$status = $this->cart->add ( $goods_id, $goods_title, abs($goods_total), $goods_price, $goods_attr );
			
			//处理拼团
			//dump('grouppurchase'.$goods_id);
			if($status){
				echo $this->getCount();
			}
		}
		
	}
	
	
	//检测库存
	public function checkStock($goods_id, $num = 1, $op = 'insert'){
		$productModel=D('Product');
		$cartdata = $this->cart->readCart ();
			if($this->user_id>0){
				$this->savetodb();
				$cartdata=$this->readfromdb();
			}
		if($op == 'insert'){
			$num += $cartdata[$goods_id][2];
		}

		$Product_stockModel = M('Product_stock');
		$attr = explode(':', $goods_id);
		$stock = $productModel -> where(array('id' => $attr[0])) -> find();
		//自动上架
		if($stock['starttime'] != ''){
			if(time() < $stock['starttime']){
				exit('当前活动还没有开始！');
			}
		}

		
		if($stock['levelBuy'] > 0){
			$member = M('Member') -> where(array('id' => $this->user_id)) -> find();
			if($stock['levelBuy'] > $member['level']){
				exit('当前等级不能购买！');
			}
		}
		
		//自动下架
		if($stock['timeout'] != ''){
			$Cache = false;
			if(time() > $stock['timeout'] && $stock['timeout'] != 0){
				$productModel->where(array('id'=>$stock['id']))->data(array('status' => 0))->save(); 
				exit('当前活动已经结束');
			}
		}
		
		//echo $stock['limitBuy'];exit;
		//限购
		if($stock['minBuy'] > 0 && $stock['minBuy'] > $num){
			exit($stock['title'].'最小购买量为：'.$stock['minBuy'].'');
		}
		
		
		if($stock['limitBuy'] > 0){
			
			
			if(empty($cartdata)){
				$nums = M('Sale') -> where(array('member_id' => $this->user_id, 'product_id' => $attr[0])) -> sum('num');
				if($stock['limitBuy'] < $nums+$num){
					exit($stock['title'].'限购'.$stock['limitBuy'].'件!');
				}
			}
			
			foreach($cartdata as $k=>$v){
				$arr = explode(':',$v[0]);
				
				$num1 = 0;
				if($stock['id'] == $arr[0]){
					$num1 += M('Sale') -> where(array('member_id' => $this->user_id, 'product_id' => $arr[0])) -> sum('num');
					if($op == 'insert'){
					    $num1 += $v[2]+$num;
					}else{
						$num1 += $num;
					}
				}
				//if(__SITEID__ == 99){exit($num1.'个');}
				if($stock['limitBuy'] < $num1){
					exit($stock['title'].'限购'.$stock['limitBuy'].'次!');
				}
				
				
			} 
		}
		
		
		if($attr[1] == ''){
			
			
			if($stock['status'] == 0){
				exit('商品已经下架');
			}
			if($stock['stocks'] < $num){
			    $ret = "库存不足！";
				exit($ret);
			}
		}else{
			
			if($stock['status'] == 0){
				exit('商品已经下架');
			}
			$stock = $Product_stockModel -> where(array('product_id' => $attr[0],'attrList' => array('in',parseAttrId(explode(';',$attr[1]))))) -> find();
			
			if($stock['stock'] < $num){
			    $ret = "库存不足！";
				exit($ret);
			}
		}
		
		
		
		
		
		
		
		
		
		//exit('请选择　'.implode('　', $sku).'　再加入购物车！');
	}
	
	
	//检测库存
	public function checkStockCreateOrder($goods_id, $num = 1, $attrib = ''){
		$productModel=D('Product');
		$Product_stockModel = M('Product_stock');
		$attr[0] = $goods_id;
		$attr[1] = $attrib;
		$stock = $productModel -> where(array('id' => $attr[0])) -> find();
		if($attr[1] == ''){
			if($stock['stocks'] < $num){
			    return false;
			}
		}else{
			$stock = $Product_stockModel -> where(array('product_id' => $attr[0],'attrList' => array('in',parseAttrId(explode(';',$attr[1]))))) -> find();
			//echo $productModel -> 
			if($stock['stock'] < $num){
			    return false;
			}
		}
		return true;
	}
	
	
	//删除物品
	public function delete(){
		if($this->_post('cart')){
			foreach($this->cartDBdata as $v){
				$this->cart->add($v[0],$v[1],$v[2],$v[3],$v[4]);
			}
			$this->clearfromdb();
			$status = $this->cart->delete($this->_post('id'));
			if($status){
			    $ret['status'] = 1;
				
				$cartdata = $this->cart->readCart ();
				if($this->user_id>0){
					$this->savetodb();
					$cartdata=$this->readfromdb();
				}
				$ret['total'] = $this->getTotal($cartdata);
				echo json_encode($ret);
			}else{
				echo $status;
			}
		}
	}
	
	// 更新物品
	public function update() {
		if($this->_post('cart')){
			$goods_id=$this->_post('id');
			$goods_title=$this->_post('title');
			$goods_total=$this->_post('total');
			$goods_price=$this->_post('price');
			$goods_attr=$this->_post('attr');
			$this -> checkStock($goods_id, $goods_total, 'update');
			$insertdata = array();
			foreach($this->cartDBdata as $v){
				$insertdata[] = array($v[0],$v[1],$v[2],$v[3],$v[4]);
			}
			$this->cart->insert($insertdata);
			$this->clearfromdb();
			$status = $this->cart->update ( array($goods_id, $goods_title, abs($goods_total), $goods_price, $goods_attr) );
			
			if($status){
				$cartdata = $this->cart->readCart ();
				if($this->user_id>0){
					$this->savetodb();
					$cartdata=$this->readfromdb();
				}
				echo $this->getTotal($cartdata);
			}else{
				echo $status;
			}
		    
		}
	}
	
	
	
	//清空
	protected function clearCart(){
		$this->clearfromdb();
		$this->cart->clear();
	}
	// 清空物品
	public function clear(){
		$this->clearCart();
		$this->success ('成功清空购物车', U ( 'index' ) );
	}
	
	// 物品存入数据库
	public function savetodb() {
		$cartdb = M ( 'Cart' );
		$data = $cartdb->where ( $this->condition )->find ();
		//dump (unserialize($data['cartdata']));
		if ($data != NULL) {
		    //合并COOKIE和DB数据
			$cartDBdata=unserialize($data['cartdata']);
			$insertdata = array();
			//foreach会出现502，改为组合数据后直接setcookie
			foreach($cartDBdata as $v){//dump($v);
			    //$this->cart->delete($v[0]);
				$insertdata[] = array($v[0],$v[1],$v[2],$v[3],$v[4]);
			}$this->cart->insert($insertdata);
			// 要修改的数据对象属性赋值
			$cartdata = $this->cart->readCart ();
			$this->cart->clear();
		    $cartContentString = serialize ( $cartdata );
			$data ['cartdata'] = $cartContentString;
			$data ['updatetime'] = time ();
			$status = $cartdb->where ( $this->condition )->save ( $data );
		} else {
			// 要修改的数据对象属性赋值
			$data ['user_id'] = $this->user_id;
			$data ['cartdata'] = $cartContentString;
			$data ['updatetime'] = time ();
			$status = $cartdb->add ( $data );
		}
		
		return $status;
	}
	
	// 从数据库读取物品
	public function readfromdb() {
		$cartdb = M ( 'Cart' );
		$data = $cartdb->where ( $this->condition )->find ();
		
		if ($data) {
			$cartArray = unserialize ( $data ['cartdata'] );
		}
		return $cartArray;
	}
	
	// 清空数据库购物车
	public function clearfromdb() {
		$cartdb = M ( 'cart' );
		$data = $cartdb->where ( $this->condition )->find ();
		
		if ($data) {
			$data ['cartdata'] = '';
			$cartdb->where ( $this->condition )->save ( $data );
		}
	}
	
	
	public function getCount(){
		$ret = 0;
		$cartdata = $this->cart->readCart ();
		if($this->user_id>0){
			$this->savetodb();
			$cartdata=$this->readfromdb();
		}
		foreach($cartdata as $k=>$v){
			$ret += $v[2];
		}
		echo $ret;
	}
	
	//获取商品总数量
	public function getnum($cartdata){
	   		
	   $znum = 0;
	   $productList = $this->getAllProduct($cartdata);

	   foreach($productList as $v){
		   
				$znum = $znum+$v['num'];
			}
	   
	   return $znum;
	}
	
	//是否能用积分抵现
	private function canIntegralPay($product_id){
		//拼团商品不能抵现
		$Bargain = M('Bargain') -> where(array('inventory' => array('gt', 0), 'product_id' => $product_id, 'state' => 1)) -> find();
		//砍价商品不能抵现
		$Grouppurchase = M('Grouppurchase') -> where(array('stock' => array('gt', 0), 'product_id' => $product_id, 'status' => 1)) -> find();
		
		if($Bargain || $Grouppurchase){
			return false;
		}
		return true;
	}
	
}